﻿namespace Pibby.Core
{
	using System.IO;
	using dogd;
	using invrt;
	using Pibby.Core.IO;
	using Pibby.Core.Persistence;

	public static class RepositoryFinder
	{
		public static IPodcastRepository FindRepository (IUserSettings settings, string fileName, IFolderCollection searchPaths, IFolder defaultRepository)
		{
			IPodcastRepository repository = null;

			try
			{
				// now try to find the repository for stored subscriptions, episodes etc.
				if (string.IsNullOrEmpty(settings.RepositoryPath))
					settings.RepositoryPath = defaultRepository.PathToFile (fileName);

				IFolderFactory factory = InversionOfController.Factory.CreateTypeOf<IFolderFactory>();

				IFile file = factory.GetFile(settings.RepositoryPath);

				if (!file.Exists)
				{
					// try to find one
					IFile repositoryFile = FileSearcher.Find(fileName, searchPaths);
					settings.RepositoryPath = repositoryFile.Path;
				}

				try
				{
					// try to open it...
					var tempRepository = new PodcastRepository(settings.RepositoryPath);

					// and check it's ok???
					ApplicationVersion v = tempRepository.GetVersion ();

					repository = tempRepository;
				}
				catch (PersistenceException)
				{
					// something when wrong - delete the file (!) and recreate it...
					IFile corruptFile = factory.GetFile(settings.RepositoryPath);
					corruptFile.Delete();

					repository = CreateDefaultSubscriptionFile(settings.RepositoryPath);
				}
			}
			catch (FileNotFoundException)
			{
				// can't find a repository - create a new, blank one.
				settings.RepositoryPath = defaultRepository.PathToFile(fileName);
				repository = CreateDefaultSubscriptionFile(settings.RepositoryPath);
			}

			return repository;
		}

		private static IPodcastRepository CreateDefaultSubscriptionFile(string fileLocation)
		{
			var repository = new PodcastRepository(fileLocation);

			repository.CreateNewDatabase();

			return repository;
		}

	}
}
